package ua.com.infopulse.sevices;

import ua.com.infopulse.Actions;
import ua.com.infopulse.Config;
import ua.com.infopulse.db.DBGetter;
import ua.com.infopulse.observers.LocationListener;
import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

/**
 * @author Andrew.Nazymko
 */
public class GpsUpdater extends IntentService {
    private static String TAG = GpsUpdater.class.getSimpleName();

    public GpsUpdater(String name) {
        super(name);
    }

    public GpsUpdater() {
        super(TAG);
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        LocationListener gpsListener = new LocationListener(getApplication());
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
        getApplication().sendBroadcast(new Intent(Actions.GPS_UPDATER_STARTED));
        while (Config.isGPSEnabled) {
            try {
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (lastKnownLocation != null) {
                    double latitude = lastKnownLocation.getLatitude();
                    Log.d(TAG, "latitude = " + latitude);
                    double longitude = lastKnownLocation.getLongitude();
                    Log.d(TAG, "longitude = " + longitude);
                    DBGetter.getDTM().addCheckIN(lastKnownLocation, "GPS point");
                    Log.d(TAG, "GPS location taken");
                    Config.isGPSEnabled = false;
                } else {
                    Log.d(TAG, "Unknown last location");
                }

                Thread.sleep(Config.gpsUpdateTime);
            } catch (InterruptedException e) {
                Log.e("EXCEPTION", this.getClass().getName(), e);
                //Unexpected exit and remove gps tracking
                removeUpdate(locationManager, gpsListener);
            }
        }
        removeUpdate(locationManager, gpsListener);
    }

    private void removeUpdate(LocationManager locationManager, LocationListener gpsListener) {
        locationManager.removeUpdates(gpsListener);
    }
}
